package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONString;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.customer.dto.response.InstitutionStaffResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.constants.HeaderConstants;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.domain.InstitutionStaff;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    private final HttpServletRequest httpServletRequest;
    @Resource
    private AddressBookMapper addressBookMapper;

    public AddressBookServiceImpl(HttpServletRequest httpServletRequest) {
        this.httpServletRequest = httpServletRequest;
    }

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public void addressBook(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        if (Objects.isNull(addressBookUpsertReqDTO)) {
            throw new BadRequestException("地址信息不能为空");
        }
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        AddressBook addressBook = BeanUtils.toBean(addressBookUpsertReqDTO, AddressBook.class);
        String[] split = addressBookUpsertReqDTO.getLocation().split(",");
        addressBook.setLat(Double.valueOf(split[0]));
        addressBook.setLon(Double.valueOf(split[1]));
        addressBook.setUserId(currentUserInfo.getId());
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setUpdateBy(currentUserInfo.getId());
        addressBook.setCreateBy(currentUserInfo.getId());
        boolean flag = save(addressBook);
        if (!flag){
            throw new BadRequestException("添加失败");
        }

    }

    @Override
    public void updateAddressBookById(AddressBookUpsertReqDTO addressBookUpsertReqDTO,Long id) {
        if (Objects.isNull(addressBookUpsertReqDTO) || CollectionUtil.isEmpty(Collections.singleton(id))) {
            throw new BadRequestException("地址信息不能为空");
        }
        AddressBook addressBook = getById(id);
        addressBook.setAddress(addressBookUpsertReqDTO.getAddress());
        addressBook.setCity(addressBookUpsertReqDTO.getCity());
        addressBook.setCounty(addressBookUpsertReqDTO.getCounty());
        addressBook.setIsDefault(addressBookUpsertReqDTO.getIsDefault());
        addressBook.setName(addressBookUpsertReqDTO.getName());
        addressBook.setPhone(addressBookUpsertReqDTO.getPhone());
        addressBook.setProvince(addressBookUpsertReqDTO.getProvince());
        addressBook.setUpdateTime(LocalDateTime.now());

        boolean flag = updateById(addressBook);
        if (!flag){
            throw new BadRequestException("修改失败");
        }
    }

    @Override
    public PageResult<AddressBook> pageQueryO(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        //TODO
        //排序条件没看出来
        if (Objects.isNull(addressBookPageQueryReqDTO)) {
            throw new BadRequestException("分页信息不能为空");
        }
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        Long userId = currentUserInfo.getId();
        LambdaQueryWrapper<AddressBook> lambdaQueryWrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId, userId);
        Page<AddressBook> serveTypePage = baseMapper.selectPage(page, lambdaQueryWrapper);

        return PageUtils.toPage(serveTypePage, AddressBook.class);
    }

    @Override
    public AddressBook echoById(Long id) {
        if (Objects.isNull(id)){
            throw new BadRequestException("地址id不能为空");
        }
        AddressBook addressBook = getById(id);
        if (Objects.isNull(addressBook)){
            throw new BadRequestException("地址信息不存在");
        }
        return addressBook;
    }

    @Override
    public void batchDeleteByIds(List<Long> ids) {
        boolean flag = removeByIds(ids);
        if (!flag){
            throw new BadRequestException("删除失败");
        }
    }

    @Override
    public void updateDefault(Integer flag, Long id) {

        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        AddressBook addressBook = getById(id);
        if (addressBook.getIsDefault().equals(flag)){
            throw new BadRequestException("不可重复修改");
        }
        int count = 0;
        List<AddressBook> addressBookList = addressBookMapper.getListByUserId(currentUserInfo.getId());
        for (AddressBook addressBook1 : addressBookList) {
            if (addressBook1.getIsDefault().equals(CertificationStatusEnum.PROGRESSING.getStatus())){
                count++;
            }
        }
        if(flag == 0){
            addressBook.setIsDefault(flag);
            updateById(addressBook);
        } else if (flag == 1) {
            if (count >= CertificationStatusEnum.PROGRESSING.getStatus()){
                throw new BadRequestException("默认地址已存在，不可设置多个默认地址");
            }
            addressBook.setIsDefault(flag);
            updateById(addressBook);
        }


    }

    @Override
    public AddressBook defaultAddress() {
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        List<AddressBook> addressBookList = addressBookMapper.getListByUserId(currentUserInfo.getId());
        for (AddressBook addressBook : addressBookList) {
            if (addressBook.getIsDefault().equals(CertificationStatusEnum.PROGRESSING.getStatus())){
                return addressBook;
            }
        }
        throw new BadRequestException("没有默认地址");
    }
}
